package com.starry.core.tenant.core.service.impl;

import com.starry.core.common.execption.ServiceException;
import com.starry.core.redis.service.RedisService;
import com.starry.core.tenant.core.aop.TenantIgnore;
import com.starry.core.tenant.core.service.TenantFrameworkService;
import com.starry.db.core.enums.DBEnableDisableStatusEnum;
import com.starry.module.system.api.tenant.SysTenantApi;
import com.starry.module.system.api.tenant.domain.vo.SysTenantDtlVo;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.starry.core.tenant.core.redis.RedisKeyConstants.SYS_TENANT_DETAILS;

/**
 * 获取租户信息
 *
 * @author xiaoke
 */
@Service
public class TenantFrameworkServiceImpl implements TenantFrameworkService {

    private final SysTenantApi sysTenantApi;
    private final RedisService redisService;

    public TenantFrameworkServiceImpl(SysTenantApi sysTenantApi, RedisService redisService) {
        this.sysTenantApi = sysTenantApi;
        this.redisService = redisService;
    }


    @Override
    @TenantIgnore
    public void validTenant(Long id) {
        String key = SYS_TENANT_DETAILS + id;
        if (redisService.hasKey(key)) {
            SysTenantDtlVo tenantDtlVo = redisService.getCacheObject(key);
            validTenant(tenantDtlVo);
            return;
        }
        SysTenantDtlVo tenantDtlVo = sysTenantApi.findById(id).getData();
        // 缓存（租户变更系统服务会删除该缓存）
        redisService.setCacheObject(key, tenantDtlVo);
        validTenant(tenantDtlVo);
    }

    /**
     * 校验租户是否可用
     *
     * @param tenantDtl 租户详情
     */
    private void validTenant(SysTenantDtlVo tenantDtl) {
        if (tenantDtl == null) {
            throw new ServiceException("租户不存在");
        }
        if (DBEnableDisableStatusEnum.isDisable(tenantDtl.getStatus())) {
            throw new ServiceException("租户已禁用");
        }
        if (tenantDtl.getExpireTime() != null && tenantDtl.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException("租户已到期");
        }
    }
}
